package com.you.bio.objectio;

import com.you.bio.constant.Constants;

import java.io.*;

public class ObjectIODemo {

    public static void main(String[] args) throws Exception {
        Student student = new Student();
        student.setStuNo(1001);
        student.setStuName("tom");
        writeObjectToFile(student, "F:\\Idea_Workspace\\Java_Senior_Projects\\java-bio.project\\test_file_dir\\Student" +
                ".txt");
        System.out.println("------------读取对象-----------");
        Student student1 = (Student) readObjectFromFile("F:\\Idea_Workspace\\Java_Senior_Projects\\java-bio" +
                ".project\\test_file_dir\\Student" +
                ".txt");
        System.out.println(student1.getStuNo() + "," + student1.getStuName());
    }

    public static void writeObjectToFile(Object obj, String filePath) {
        File file = new File(filePath);
        try {
            ObjectOutputStream objOutputStream =
                    new ObjectOutputStream(new FileOutputStream(file));
            //将对象写入文件
            objOutputStream.writeObject(obj);
            //关闭流
            objOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object readObjectFromFile(String filePath) {
        Object obj = null;
        File file = new File(filePath);
        try {
            ObjectInputStream objectInputStream =
                    new ObjectInputStream(new FileInputStream(file));
            //将对象写入文件
            obj = objectInputStream.readObject();
            //关闭流
            objectInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
